//
//  HJFlutteAlertController.m
//  KaiChat
//
//  Created by lx on 2024/3/27.
//

#import "HJFlutteAlertController.h"
#import "HJFlutterManager.h"
#import "HJFlutterMethod.h"

#if LOADFLUTTER

#import <Flutter/Flutter.h>

#endif


@interface HJFlutteAlertController ()

#if LOADFLUTTER

@property (nonatomic, strong) FlutterViewController *flutterViewController;

#endif

@property (nonatomic, strong) HJFlutterPageName name;

@end

@implementation HJFlutteAlertController


- (HJFlutteAlertController *)initWithName:(HJFlutterPageName)name {
    if (self = [super init]) {
        _name = name;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = UIColor.clearColor;
    
#if LOADFLUTTER

    HJFlutterManager.sharedManager.containController = self;
    FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:HJFlutterManager.sharedManager.mainEngine nibName:nil bundle:nil];
    _flutterViewController = flutterViewController;
    flutterViewController.view.frame = self.view.bounds;
    [self.view addSubview:flutterViewController.view];
    [self addChildViewController:flutterViewController];

#endif
    
    [self openPageWithName:self.name];
//    NSLog(@"_flutterController = %@", flutterViewController);
}

- (void)openPageWithName:(HJFlutterPageName)name {
    
#if LOADFLUTTER
    
    FlutterMethodChannel *walletChannel = [FlutterMethodChannel methodChannelWithName:HJFlutterManager.sharedManager.channelName binaryMessenger:HJFlutterManager.sharedManager.mainEngine.binaryMessenger];
    [walletChannel invokeMethod:HJFlutterMethod.setBaseInfo arguments:[HJFlutterManager.sharedManager getFlutterMessageWithPage:name arguments:_arguments] result:^(id  _Nullable result) {
        NSLog(@"result = %@", result);
    }];
    
#endif
    
}

 
- (void)dealloc {
    
#if LOADFLUTTER
    _flutterViewController = nil;
    HJFlutterManager.sharedManager.mainEngine.viewController = nil;
#endif
    NSLog(@"销毁flutterController, 和引擎置空");
    NSLog(@"%s", __func__);
}
 

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}

 
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
